package com.xjrsoft.common.utils;


import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.request.OapiV2DepartmentListsubRequest;
import com.dingtalk.api.request.OapiV2UserListRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiV2DepartmentListsubResponse;
import com.dingtalk.api.response.OapiV2UserListResponse;
import com.taobao.api.ApiException;
import com.xjrsoft.config.WechatEnterpriseConfig;
import com.xjrsoft.module.organization.dto.WeChatDepartDto;
import com.xjrsoft.module.organization.dto.WeChatUserDto;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Component
@AllArgsConstructor
public class WeChatUtil {

    //获取通讯录或发消息token
    public String getWeChatToken() {
        WechatEnterpriseConfig wechatEnterpriseConfig = SpringUtil.getBean(WechatEnterpriseConfig.class);

        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("corpid", wechatEnterpriseConfig.getAppKey());
        paramMap.put("corpsecret", wechatEnterpriseConfig.getAppSecret());
        String result = HttpUtil.get("https://qyapi.weixin.qq.com/cgi-bin/gettoken", paramMap);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String token = jsonObject.get("access_token").toString();
        return token;
    }

    //根据所有部门信息
    public List<WeChatDepartDto> getWeChatDepartmentList(Long dept_id) {
        String token = this.getWeChatToken();
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("access_token", token);
        if (dept_id != null) {
            paramMap.put("id", dept_id);
        }
        String result = HttpUtil.get("https://qyapi.weixin.qq.com/cgi-bin/department/list", paramMap);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject.getLong("errcode") != 0L) {
            throw new RuntimeException(jsonObject.getString("errmsg"));
        }
        Object department = jsonObject.get("department");
        List<WeChatDepartDto> weChatDepartDtos = JSONObject.parseArray(department.toString(), WeChatDepartDto.class);
        return weChatDepartDtos;
    }

    //获取部门的所有用户信息
    public List<WeChatUserDto> getWeChatUsersOfDepartment(Long departmentId) {
        String token = this.getWeChatToken();
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("access_token", token);
        paramMap.put("department_id", departmentId);
//        paramMap.put("fetch_child", 1);
        String result = HttpUtil.get("https://qyapi.weixin.qq.com/cgi-bin/user/list", paramMap);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject.getLong("errcode") != 0L) {
            throw new RuntimeException(jsonObject.getString("errmsg"));
        }
        Object department = jsonObject.get("userlist");
        List<WeChatUserDto> weChatUserDtos = JSONObject.parseArray(department.toString(), WeChatUserDto.class);
        return weChatUserDtos;
    }

    //获取通讯录或发消息token
    public String getDingTalkToken(String appKey, String appSecret) {
        OapiGettokenResponse response = null;
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
            OapiGettokenRequest request = new OapiGettokenRequest();
            request.setAppkey(appKey);
            request.setAppsecret(appSecret);
            request.setHttpMethod("GET");
            response = client.execute(request);
        } catch (ApiException e) {
            throw new RuntimeException("获取钉钉token报错！", e);
        }
        return response.getAccessToken();
    }

    //根据所有部门信息
    public List<OapiV2DepartmentListsubResponse.DeptBaseResponse> getDingTalkDepartmentList(String appKey, String appSecret, Long deptId) {
        String token = this.getDingTalkToken(appKey, appSecret);
        List<OapiV2DepartmentListsubResponse.DeptBaseResponse> deptBaseResponselist=new ArrayList<>();
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub");
            OapiV2DepartmentListsubRequest req = new OapiV2DepartmentListsubRequest();
//            req.setDeptId(departmentId);
            req.setLanguage("zh_CN");
            if (ObjectUtils.isNotEmpty(deptId)) {
                req.setDeptId(deptId);
            }
            OapiV2DepartmentListsubResponse response = client.execute(req, token);
            if(!response.isSuccess()){
                throw new Exception(response.getErrmsg());
            }
            deptBaseResponselist = response.getResult();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        return deptBaseResponselist;
    }

    //获取部门的所有用户信息
    public List<OapiV2UserListResponse.ListUserResponse> getDingTalkUsersOfDepartment(Long departmentId, String appKey, String appSecret) {
        String token = this.getDingTalkToken(appKey, appSecret);
        List<OapiV2UserListResponse.ListUserResponse> userResponseList = new ArrayList<>();
        try {
            Long cursor=0L;
            Boolean hasMore=true;
            while (hasMore) {
                DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/list");
                OapiV2UserListRequest req = new OapiV2UserListRequest();
                req.setDeptId(departmentId);
                req.setCursor(cursor);
                req.setSize(100L);
                req.setOrderField("modify_desc");
                req.setContainAccessLimit(false);
                req.setLanguage("zh_CN");
                OapiV2UserListResponse rsp = client.execute(req, token);
                userResponseList.addAll(rsp.getResult().getList());
                hasMore=rsp.getResult().getHasMore();
                cursor=rsp.getResult().getNextCursor();
            }
        } catch (ApiException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        return userResponseList;
    }
}
